$(function(){
	// 手机号码验证
	jQuery.validator.addMethod("mobile", function(value, element) {
	    var length = value.length;
	    var mobile =  /^(((13[0-9]{1})|(15[0-9]{1}))+\d{8})$/
	    return this.optional(element) || (length == 11 && mobile.test(value));
	}, "手机号码格式错误");  

	// 电话号码验证   
	jQuery.validator.addMethod("phone", function(value, element) {
	    var tel = /^(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$/;
	    return this.optional(element) || (tel.test(value));
	}, "电话号码格式错误");

	// 邮政编码验证   
	jQuery.validator.addMethod("zipCode", function(value, element) {
	    var tel = /^[0-9]{6}$/;
	    return this.optional(element) || (tel.test(value));
	}, "邮政编码格式错误");
	
	// QQ号码验证   
	jQuery.validator.addMethod("qq", function(value, element) {
	    var tel = /^[1-9]\d{4,9}$/;
	    return this.optional(element) || (tel.test(value));
	}, "qq号码格式错误");
	
	
	// 字母和数字的验证
	jQuery.validator.addMethod("chrnum", function(value, element) {
	    var chrnum = /^([a-zA-Z0-9]+)$/;
	    return this.optional(element) || (chrnum.test(value));
	}, "只能输入数字和字母(字符A-Z, a-z, 0-9)");
	
	// 中文的验证
	jQuery.validator.addMethod("chinese", function(value, element) {
	    var chinese = /^[\u4e00-\u9fa5]+$/;
	    return this.optional(element) || (chinese.test(value));
	}, "只能输入中文");
	
	// 下拉框验证
	$.validator.addMethod("selectNone", function(value, element) {
	    return value == "请选择";
	}, "必须选择一项");
	
	// 字节长度验证
	jQuery.validator.addMethod("byteRangeLength", function(value, element, param) {
	    var length = value.length;
	    for (var i = 0; i < value.length; i++) {
	        if (value.charCodeAt(i) > 127) {
	            length++;
	        }
	    }
	    return this.optional(element) || (length >= param[0] && length <= param[1]);
	}, $.validator.format("请确保输入的值在{0}-{1}个字节之间(一个中文字算2个字节)"));
})
var FormValidation = function () {
    return {
        //main function to initiate the module
        init: function () {

            var form2 = $('#form_sample_2');
            var error2 = $('.alert-error', form2);
            var success2 = $('.alert-success', form2);

            form2.validate({
                errorElement: 'span', //default input error message container
                errorClass: 'help-inline', // default input error message class
                focusInvalid: false, // do not focus the last invalid input
                ignore: "",
                rules: {
                    businessoper: {
                        required: true,                      
                    },
                    custname: {
                        required: true,
                        //mobile:true  //自定义验证标签
                    },
                    reagreement:{
                    	required:true,
                    },
                    markorgan:{
                    	required:true,
                    },
                    kuorgan:{
                    	required:true,
                    },
                    busyperson:{
                    	required:true,
                    },
                    clientprop:{
                    	required:true,
                    }, 
                    payways: {
                        required: true
                    },                  
                    moneykind: {
                        required: true
                    },                  
                    seriveway: {
                        required: true
                    },                 
                    addresskind: {
                        required: true,
                    },
                    sendcompy:{
                    	required: true,
                    },
                    billtype: {
                        required: true
                    },
                    
                    service: {
                        required: true,
                        minlength: 2
                    }
                },
				//错误验证信息 name值
                messages: { 
                    businessoper: {
                        required: "请选择业务流程",
                    },
                    custname:{
                    	required: "请选择客户名称"
                    },
                    reagreement:{
                    	required:"请选择一种收款协议"
                    },
                    markorgan:{
                    	required:"请选择一种销售组织"
                    },
                    kuorgan:{
                    	required:"请选择一种库存组织"
                    },
                    busyperson:{
                    	required:"请选择一个业务人员"
                    },
                    clientprop:{
                    	required:"请选择一种客户属性"
                    },
                    payways:{
                    	required:"请选择一种支付方式"
                    },
                    moneykind:{
                    	required:"请选择一种支付方式"
                    },
                    seriveway:{
                    	required:"请选择一种配送方式"
                    },
                    addresskind:{
                    	required:"请选择要配送的地址"
                    },
                    sendcompy:{
                    	required:"请选择一家发货公司"
                    },
                    billtype:{
                    	required:"请选择一种发票类型"
                    }
                },

                errorPlacement: function (error, element) { // render error placement for each input type
                    if (element.attr("name") == "billtype") {                     	
                    	// 发票类型
                        error.addClass("no-left-padding").insertAfter("#form_2_membership_error");
                    } else if (element.attr("name") == "service") { // for uniform checkboxes, insert the after the given container
                        error.addClass("no-left-padding").insertAfter("#form_2_service_error");
                    } else {
                        error.insertAfter(element); // for other inputs, just perform default behavoir
                    }
                },

                invalidHandler: function (event, validator) { //display error alert on form submit   
                    success2.hide();
                    error2.show();
                    App.scrollTo();
                },

                highlight: function (element) { // hightlight error inputs
                    $(element)
                        .closest('.help-inline').removeClass('ok'); // display OK icon
                    $(element)
                        .closest('.control-group').removeClass('success').addClass('error'); // set error class to the control group
                },

                unhighlight: function (element) { // revert the change dony by hightlight
                    $(element).closest('.control-group').removeClass('error'); // set error class to the control group
                },

                success: function (label) {
                    if (label.attr("for") == "service" || label.attr("for") == "membership") { // for checkboxes and radip buttons, no need to show OK icon
                        label
                            .closest('.control-group').removeClass('error').addClass('success');
                        label.remove(); // remove error label here
                    } else { // display success icon for other inputs
                        label
                            .addClass('valid').addClass('help-inline ok') // mark the current input as valid and display OK icon
                        .closest('.control-group').removeClass('error').addClass('success'); // set success class to the control group
                    }
                },

                
                submitHandler:function(form){
                	//
                	layer.open({
					  	type:1,
						title: '新增配送地址',
						area: ['610px', '410px'], //宽高
						//content:$('#id名'),
			//			yes: function(index, layero){
			//			},
			//			btn2: function(index, layero){
			//			    //return false 开启该代码可禁止点击该按钮关闭
			//			}
					});
                	//提交
					$.ajax({
						url: "/",
						type : "POST", 
            			dataType :"json",
						data:$('#form_sample_2').serialize(),
						success: function(data){
			                success2.show();
			                error2.hide();
						},
		               	error: function(data){
							layer.msg('ERROR!',{icon:2,time:1500});
						}
					});
				}

            });
			
			//新增收货地址 验证	
            var error3 = $('.alert-error', $('#form_address'));
            var success3 = $('.alert-success', $('#form_address'));
			$('#form_address').validate({
				errorElement: 'span', //default input error message container
                errorClass: 'help-inline', // default input error message class
                focusInvalid: false, // do not focus the last invalid input
                ignore: "",
                rules: {
                    areakind: {
                        required: true,                      
                    },
                    detailRess: {
                        required: true,
                    },
                    receivName:{
                    	required:true,
                    },
                    mobilePhone:{
                    	required:true,
                    	mobile:true  //自定义验证标签
                    }
                    
                },
				//错误验证信息 name值
                messages: { 
                    areakind: {
                        required: "请选择您的所在地区",
                    },
                    detailRess:{
                    	required: "详细地址不能为空"
                    },
                    receivName:{
                    	required:"收货人姓名不能为空"
                    },
                    mobilePhone:{
                    	required:"手机号码不能为空"
                    }                   
                },

                errorPlacement: function (error, element) { // render error placement for each input type
                    if (element.attr("name") == "qt") {                     	
                    	// 发票类型
                        error.addClass("no-left-padding").insertAfter("#form_2_membership_error");
                    } else if (element.attr("name") == "service") { // for uniform checkboxes, insert the after the given container
                        error.addClass("no-left-padding").insertAfter("#form_2_service_error");
                    } else {
                        error.insertAfter(element); // for other inputs, just perform default behavoir
                    }
                },

                invalidHandler: function (event, validator) { //display error alert on form submit   
                    success3.hide();
                    error3.show();
                    App.scrollTo();
                },

                highlight: function (element) { // hightlight error inputs
                    $(element)
                        .closest('.help-inline').removeClass('ok'); // display OK icon
                    $(element)
                        .closest('.control-group').removeClass('success').addClass('error'); // set error class to the control group
                },

                unhighlight: function (element) { // revert the change dony by hightlight
                    $(element).closest('.control-group').removeClass('error'); // set error class to the control group
                },

                success: function (label) {
                    if (label.attr("for") == "service" || label.attr("for") == "membership") { // for checkboxes and radip buttons, no need to show OK icon
                        label
                            .closest('.control-group').removeClass('error').addClass('success');
                        label.remove(); // remove error label here
                    } else { // display success icon for other inputs
                        label
                            .addClass('valid').addClass('help-inline ok') // mark the current input as valid and display OK icon
                        .closest('.control-group').removeClass('error').addClass('success'); // set success class to the control group
                    }
                },
                submitHandler:function(form){
	                var area = $.trim($(".c-areakind").val());
				  	var dess = $.trim($(".c-detailress").val());
				  	var rename = $.trim($(".c-rename").val())
				  	var telphone = $.trim($(".c-telphone").val())
				  	var landtel = $.trim($(".c-landtel").val());
				  	
				  	if(!area){
				  		layer.msg("请选择省份");
				  		return false;
				  	}else{
				  		console.info("选择的省份:"+ area)
				  	}
	            	//提交
					$.ajax({
						url: "/",
						type : "POST", 
	        			dataType :"html",
						data:$('#form_address').serialize(),
						success: function(data){
							//获取父层
							var index = parent.layer.getFrameIndex(window.name);
							//刷新父层
							parent.location.reload();
							//关闭弹出层
							parent.layer.close(index);
			                console.info(data)
						},
		               	error: function(data){
							layer.msg('ERROR!',{icon:2,time:1000});
						}
					});
				},
				
            });
			
			//修改密码 /*2018-7-24*/
            var error2 = $('.alert-error', $('#form_updataPwd'));
            var success2 = $('.alert-success', $('#form_updataPwd'));
            $('#form_updataPwd').validate({
                errorElement: 'span', //default input error message container
                errorClass: 'help-inline', // default input error message class
                focusInvalid: false, // do not focus the last invalid input
                ignore: "",
                rules: {
                    oldpwd: {
                        required: true,                      
                    },
                    newpwd: {
                        required: true,
                        chrnum:true  //自定义验证标签
                    },
                    surepwd:{
                    	required:true,
                    	equalTo:'#newpwd', //与新密码id="newpwd"的值相同
                    }
                    
                },
				//错误验证信息 name值
                messages: { 
                    oldpwd: {
                        required: "请输入原来密码",                      
                    },
                    newpwd: {
                        required: "请输入新密码",
                    },
                    surepwd:{
                    	required:"请输入确认密码",
                    	equalTo:"与新密码必须一致" 
                    }
                },

                errorPlacement: function (error, element) { // render error placement for each input type
                    if (element.attr("name") == "billtype") {                     	
                    	// 发票类型
                        error.addClass("no-left-padding").insertAfter("#form_2_membership_error");
                    } else if (element.attr("name") == "service") { // for uniform checkboxes, insert the after the given container
                        error.addClass("no-left-padding").insertAfter("#form_2_service_error");
                    } else {
                        error.insertAfter(element); // for other inputs, just perform default behavoir
                    }
                },

                invalidHandler: function (event, validator) { //display error alert on form submit   
                    success2.hide();
                    error2.show();
                    App.scrollTo();
                },

                highlight: function (element) { // hightlight error inputs
                    $(element)
                        .closest('.help-inline').removeClass('ok'); // display OK icon
                    $(element)
                        .closest('.control-group').removeClass('success').addClass('error'); // set error class to the control group
                },

                unhighlight: function (element) { // revert the change dony by hightlight
                    $(element).closest('.control-group').removeClass('error'); // set error class to the control group
                },

                success: function (label) {
                    if (label.attr("for") == "service" || label.attr("for") == "membership") { // for checkboxes and radip buttons, no need to show OK icon
                        label
                            .closest('.control-group').removeClass('error').addClass('success');
                        label.remove(); // remove error label here
                    } else { // display success icon for other inputs
                        label
                            .addClass('valid').addClass('help-inline ok') // mark the current input as valid and display OK icon
                        .closest('.control-group').removeClass('error').addClass('success'); // set success class to the control group
                    }
                },
                
                submitHandler:function(form){
                	//修改提交
                	var oldpwd = $.trim($(".c-oldpassword").val());
				  	var newpwd = $.trim($(".c-newpwd").val());
				  	var surepwd = $.trim($(".c-surepwd").val())
				  	console.info(oldpwd + newpwd + surepwd)
					$.ajax({
						url: "/auth/update_password",
						type : "POST", 

						data: $('#form_updataPwd').serialize(),

                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                    },
						success: function(data){


                            if(data.status==0){

                                layer.msg(data.msg,{icon:2,time:1500});
                            }else{

                                success2.show();
                                error2.hide();
                                layer.msg('密码修改成功!',{icon:1,time:1500});
                                location.href='/auth/logout';
                            }

						},
		               	error: function(data){
							layer.msg('密码修改失败!',{icon:2,time:1500});

						}
					});
				}

            });		
			
            //apply validation on chosen dropdown value change, this only needed for chosen dropdown integration.
            $('.chosen, .chosen-with-diselect', form2).change(function () {
                form2.validate().element($(this)); //revalidate the chosen dropdown value and show error or success message for the input
            });

             //apply validation on select2 dropdown value change, this only needed for chosen dropdown integration.
            $('.select2', form2).change(function () {
                form2.validate().element($(this)); //revalidate the chosen dropdown value and show error or success message for the input
            });

        }

    };

}();